package cn.bonoon.handler.impl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import cn.bonoon.core.plugins.LoginRecordService;

public class LogoutSuccessHandlerImpl extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler{
	//private final static String DEFAULT_LOGOUT_TARGET_URL = "/s/login";
	
	@Autowired
	private LoginRecordService loginRecordSevice;

	public LogoutSuccessHandlerImpl(){}

	public LogoutSuccessHandlerImpl(String defaultTargetUrl){
		setDefaultTargetUrl(defaultTargetUrl);
	}
//	public LogoutSuccessHandlerImpl(LoginRecordService loginRecordSevice) {
//		super.setTargetUrlParameter(null);
//		this.loginRecordSevice = loginRecordSevice;
//	}

	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//		if(null != authentication){
//			try {
//				//如果是session超期，并且用户点击退出登录，这里就会出现authentication is null的情况
//				loginRecordSevice.logout(authentication.getName());
//			} catch (Throwable err) {
//				// 忽略所有异常情况
//				err.printStackTrace();
//				logger.error("更新退出登录记录异常", err);
//			}
//		}
		//setDefaultTargetUrl(DEFAULT_LOGOUT_TARGET_URL);
		super.handle(request, response, authentication);
	}

//	@Override
//	public void onApplicationEvent(SessionDestroyedEvent event) {
////		/String sid = event.getId();
//		try{
//			loginRecordSevice.logouWithSessionId(event.getId());
//		} catch (Throwable err) {
//			logger.error("更新退出登录记录异常", err);
//		}
//	}

}
